package com.jinxin.platform.cddatadict.service.impl;

import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cddatadict.mapper.CddatadictDictItemMapper;
import com.jinxin.platform.cddatadict.pojo.domains.DataDictItem;
import com.jinxin.platform.cddatadict.service.SysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysDictItemServiceImpl implements SysDictItemService {
    @Autowired
    private CddatadictDictItemMapper cddatadictDictItemMapper;

    @Override
    public int insert(DataDictItem dataDictItem) {
        return cddatadictDictItemMapper.insert(dataDictItem);
    }

    @Override
    public int updateByKey(DataDictItem dataDictItem) {
        return cddatadictDictItemMapper.updateByKey(dataDictItem);
    }

    @Override
    public DataDictItem selectByKey(String id) {
        return cddatadictDictItemMapper.selectByKey(id);
    }

    @Override
    public DataDictItem selectOne(HashMap param) {
        return cddatadictDictItemMapper.selectOne(param);
    }

    @Override
    public List<DataDictItem> list(HashMap param) {
        return cddatadictDictItemMapper.list(param);
    }

    @Override
    public List<DataDictItem> listPage(HashMap param) {
        return cddatadictDictItemMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return cddatadictDictItemMapper.listPageCount(param);
    }

    @Override
    public int deleteByKey(String id) {
        return cddatadictDictItemMapper.deleteByKey(id);
    }

    @Override
    public JsonResult batchDelItem(List<DataDictItem> records) {
        Set<String> idSet = new HashSet<>();
        findDeleteingId(idSet,records,records);
        //cddatadictDictItemMapper.deleteByIds(idSet);
        return JsonResult.ok("删除成功",null);
    }

    private void findDeleteingId(Set<String> idSet,List<DataDictItem> subList,List<DataDictItem> records){
        for (DataDictItem record : subList) {
            HashMap param = new HashMap();
            String id = record.getId();
            param.put("dictType", id);
            List<DataDictItem> dictItems = cddatadictDictItemMapper.list(param);
            if (!dictItems.isEmpty()) {
                // 看子项是不是已经全部选择
                int size = (int) records.stream().filter(item -> item.getDictType().equals(id)).count();
                if(size == dictItems.size()){
                    //继续查找子项
                    idSet.add(id);
                    findDeleteingId(idSet,dictItems,records);
                }
            }else {//没有子项的直接删
                idSet.add(id);
            }
        }
    }
}
